﻿using System.Data.Objects;
using System.Linq;

namespace ActivateYourGlutes.Data
{
    public class EntityFrameworkRepository<T> : EntityFrameworkRepositoryBase, IRepository<T> where T : class
    {
        private readonly ObjectSet<T> _entities;

        public EntityFrameworkRepository(string connectionString) : base(connectionString)
        {
            _entities = Context.CreateObjectSet<T>();
        }

        public EntityFrameworkRepository(EntityFrameworkRepositoryBase existingRepository) : base(existingRepository)
        {
            _entities = Context.CreateObjectSet<T>();
        }

        public IQueryable<T> Entities
        {
            get { return _entities; }
        }

        public IQueryable<T> EagerlyLoadedEntities(params string[] entities)
        {
            ObjectQuery<T> result = _entities;
            foreach(var entityReference in entities)
            {
                result = result.Include(entityReference);
            }
            return result;
        }

        public void Create(T entity)
        {
            _entities.AddObject(entity);
        }

        public void Delete(T entity)
        {
            _entities.DeleteObject(entity);
        }

        public void SaveChanges()
        {
            Context.SaveChanges();
        }
    }
}
